<template>
	<view class="container">
		<!-- 统计卡片区域 - 吸顶 -->
		<view class="stats-cards">
			<view class="stats-row">
				<view class="stat-card">
					<text class="stat-value"
						>{{ monthlyTotalHours }}
						<text style="font-size: 26rpx; font-weight: normal"
							>小时</text
						></text
					>
					<text class="stat-label">本月总工时</text>
				</view>
				<view class="stat-card">
					<text class="stat-value"
						>{{ avgDailyHours }}
						<text style="font-size: 26rpx; font-weight: normal"
							>小时</text
						></text
					>
					<text class="stat-label">平均每日</text>
				</view>
				<view class="stat-card">
					<text class="stat-value">{{ attendanceRate }}%</text>
					<text class="stat-label">本月出勤率</text>
				</view>
			</view>
		</view>
		<!-- 删除图表容器 -->
		<view style="height: 20rpx"></view>
		<hr />
		<!-- 今日记录区 -->
		<view class="today-record-section">
			<text class="section-title">今日记录</text>

			<view class="record-form">
				<view style="display: flex; justify-content: space-between; gap: auto">
					<view class="form-item">
						<text class="form-label">出勤时间</text>
						<input
							v-model.number="todayRecord.workHours"
							type="digit"
							placeholder="请输入出勤时间"
							class="form-input"
							@blur="validateInput('workHours')"
						/>
						<text class="form-unit">小时</text>
					</view>
					<view class="form-item">
						<text class="form-label">加班时间</text>
						<input
							v-model.number="todayRecord.overtimeHours"
							type="digit"
							placeholder="请输入加班时间"
							class="form-input"
							@blur="validateInput('overtimeHours')"
						/>
						<text class="form-unit">小时</text>
					</view>
				</view>
				<button
					class="save-button"
					@click="saveTodayRecord"
					:disabled="isSaving || !isInputValid"
				>
					{{ isSaving ? '保存中...' : '保存' }}
				</button>
			</view>
			<text
				v-if="errorMessage"
				class="error-message"
				>{{ errorMessage }}</text
			>
		</view>
		<hr />
		<!-- 日历区域 -->
		<view class="calendar-section">
			<view class="calendar-header">
				<text class="calendar-title">最近30天</text>
				<text class="calendar-month">{{ currentMonth }}月</text>
			</view>
			<view class="calendar-grid">
				<view class="weekdays">
					<text class="weekday">日</text>
					<text class="weekday">一</text>
					<text class="weekday">二</text>
					<text class="weekday">三</text>
					<text class="weekday">四</text>
					<text class="weekday">五</text>
					<text class="weekday">六</text>
				</view>
				<view class="calendar-days">
					<view
						v-for="(day, index) in calendarDays"
						:key="index"
						class="calendar-day"
						:class="{
							'other-month': !day.isCurrentMonth,
							'has-record': day.hasRecord,
							today: day.isToday,
						}"
						@click="editRecord(day)"
					>
						<text class="day-number">{{ day.day }}</text>
						<view
							v-if="day.hasRecord"
							class="day-hours"
						>
							<text class="hours-text">{{ day.displayHours }}</text>
						</view>
						<view
							v-else-if="day.isCurrentMonth && !day.isFuture"
							class="no-record"
						>
							<text class="no-record-text">未记录</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 编辑弹窗 -->
		<uni-popup
			ref="editPopup"
			type="center"
		>
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">编辑工时记录</text>
					<text
						class="popup-close"
						@click="closePopup"
						>×</text
					>
				</view>
				<view class="popup-body">
					<text class="popup-date">{{ currentEditDate }}</text>
					<view
						class="form-item"
						style="margin-top: 40rpx"
					>
						<text class="form-label">出勤时间</text>
						<input
							v-model.number="editRecordData.workHours"
							type="digit"
							placeholder="请输入出勤时间"
							class="form-input"
							@blur="validateEditInput('workHours')"
						/>
						<text class="form-unit">小时</text>
					</view>
					<view
						class="form-item"
						style="margin-top: 40rpx"
					>
						<text class="form-label">加班时间</text>
						<input
							v-model.number="editRecordData.overtimeHours"
							type="digit"
							placeholder="请输入加班时间"
							class="form-input"
							@blur="validateEditInput('overtimeHours')"
						/>
						<text class="form-unit">小时</text>
					</view>
					<text
						v-if="editErrorMessage"
						class="error-message"
						>{{ editErrorMessage }}</text
					>
				</view>
				<view class="popup-footer">
					<button
						class="cancel-button"
						@click="closePopup"
					>
						取消
					</button>
					<button
						class="confirm-button"
						@click="confirmEdit"
						:disabled="isEditing || !isEditInputValid"
					>
						{{ isEditing ? '修改中...' : '确认修改' }}
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

const refreshFlag = ref(0);

// 今日记录数据
const todayRecord = ref({
	workHours: 8,
	overtimeHours: 0,
});

// 状态管理
const isSaving = ref(false);
const isEditing = ref(false);
const errorMessage = ref('');
const editErrorMessage = ref('');
const editPopup = ref(null);
const currentEditDateKey = ref('');
const currentEditDate = ref('');
const editRecordData = ref({
	workHours: 8,
	overtimeHours: 0,
});

// 计算属性：输入验证
const isInputValid = computed(() => {
	return (
		todayRecord.value.workHours >= 0 &&
		todayRecord.value.overtimeHours >= 0 &&
		!errorMessage.value
	);
});

const isEditInputValid = computed(() => {
	return (
		editRecordData.value.workHours >= 0 &&
		editRecordData.value.overtimeHours >= 0 &&
		!editErrorMessage.value
	);
});

// 计算属性：本月统计数据
const monthlyTotalHours = computed(() => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	let totalHours = 0;

	// 强制依赖refreshFlag以触发重新计算
	refreshFlag.value;

	// 遍历localStorage中的所有键
	for (let i = 0; i < localStorage.length; i++) {
		const key = localStorage.key(i);
		if (key.startsWith(`workDay_${year}${month}`)) {
			try {
				const data = JSON.parse(localStorage.getItem(key));
				totalHours += (data.work || 0) + (data.overtime || 0);
			} catch (e) {
				console.error('解析数据失败:', e);
			}
		}
	}

	return totalHours.toFixed(1);
});

// 计算属性：平均日工时
const avgDailyHours = computed(() => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	let totalHours = 0;
	let recordDays = 0;

	// 强制依赖refreshFlag以触发重新计算
	refreshFlag.value;

	// 遍历localStorage中的所有键
	for (let i = 0; i < localStorage.length; i++) {
		const key = localStorage.key(i);
		if (key.startsWith(`workDay_${year}${month}`)) {
			try {
				const data = JSON.parse(localStorage.getItem(key));
				if (data.work > 0 || data.overtime > 0) {
					totalHours += (data.work || 0) + (data.overtime || 0);
					recordDays++;
				}
			} catch (e) {
				console.error('解析数据失败:', e);
			}
		}
	}

	return recordDays > 0 ? (totalHours / recordDays).toFixed(1) : '0.0';
});

// 计算属性：出勤率
const attendanceRate = computed(() => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const currentDay = now.getDate();

	let workDays = 0;
	let recordedDays = 0;

	// 强制依赖refreshFlag以触发重新计算
	refreshFlag.value;

	// 计算本月已过的工作日数量
	for (let day = 1; day <= currentDay; day++) {
		const date = new Date(year, now.getMonth(), day);
		const weekday = date.getDay();
		// 排除周末 (周日和周六)
		if (weekday !== 0 && weekday !== 6) {
			workDays++;

			// 检查是否有记录
			const dateStr = String(day).padStart(2, '0');
			const key = `workDay_${year}${month}${dateStr}`;
			const data = localStorage.getItem(key);

			if (data) {
				try {
					const record = JSON.parse(data);
					if (record.work > 0 || record.overtime > 0) {
						recordedDays++;
					}
				} catch (e) {
					console.error('解析数据失败:', e);
				}
			}
		}
	}

	return workDays > 0 ? Math.round((recordedDays / workDays) * 100) : 0;
});
// 计算属性：当前月份
const currentMonth = computed(() => {
	const now = new Date();
	return now.getMonth() + 1;
});
// 计算属性：日历数据
const calendarDays = computed(() => {
	const today = new Date();
	const currentYear = today.getFullYear();
	const currentMonth = today.getMonth();

	// 获取当前月份的第一天和最后一天
	const firstDayOfMonth = new Date(currentYear, currentMonth, 1);
	const lastDayOfMonth = new Date(currentYear, currentMonth + 1, 0);

	// 获取日历开始显示的第一天（上个月的最后一周开始）
	const startDay = new Date(firstDayOfMonth);
	startDay.setDate(firstDayOfMonth.getDate() - firstDayOfMonth.getDay());

	// 获取日历结束显示的最后一天（下个月的第一周结束）
	const endDay = new Date(lastDayOfMonth);
	endDay.setDate(lastDayOfMonth.getDate() + (6 - lastDayOfMonth.getDay()));

	const days = [];
	const currentDate = new Date(startDay);

	// 强制依赖refreshFlag以触发重新计算
	refreshFlag.value;

	// 生成日历中的每一天
	while (currentDate <= endDay) {
		const year = currentDate.getFullYear();
		const month = currentDate.getMonth();
		const day = currentDate.getDate();

		const storageKey = `workDay_${year}${String(month + 1).padStart(
			2,
			'0'
		)}${String(day).padStart(2, '0')}`;

		const isCurrentMonth = month === currentMonth && year === currentYear;
		const isToday = currentDate.toDateString() === today.toDateString();
		const isFuture = currentDate > today;

		// 从localStorage获取记录
		let hasRecord = false;
		let workHours = 0;
		let overtimeHours = 0;
		let displayHours = '';

		const storedData = localStorage.getItem(storageKey);
		if (storedData) {
			try {
				const data = JSON.parse(storedData);
				workHours = data.work || 0;
				overtimeHours = data.overtime || 0;
				hasRecord = workHours > 0 || overtimeHours > 0;

				if (hasRecord) {
					if (overtimeHours > 0) {
						displayHours = `${workHours}+${overtimeHours}`;
					} else {
						displayHours = `${workHours}`;
					}
				}
			} catch (e) {
				console.error('解析数据失败:', e);
			}
		}

		days.push({
			date: new Date(currentDate), // 创建新实例避免引用问题
			year,
			month: month + 1,
			day,
			isCurrentMonth,
			isToday,
			isFuture,
			hasRecord,
			workHours,
			overtimeHours,
			displayHours,
			storageKey,
		});

		// 移动到下一天
		currentDate.setDate(currentDate.getDate() + 1);
	}

	return days;
});

// 验证输入
function validateInput(field) {
	const value = todayRecord.value[field];
	errorMessage.value = '';

	if (value === null || value === undefined || value === '') {
		todayRecord.value[field] = 0;
		return;
	}

	if (isNaN(value) || value < 0) {
		errorMessage.value = '请输入有效数字（非负数）';
	} else {
		todayRecord.value[field] = Number(value);
	}
}

// 验证编辑输入
function validateEditInput(field) {
	const value = editRecordData.value[field];
	editErrorMessage.value = '';

	if (value === null || value === undefined || value === '') {
		editRecordData.value[field] = 0;
		return;
	}

	if (isNaN(value) || value < 0) {
		editErrorMessage.value = '请输入有效数字（非负数）';
	} else {
		editRecordData.value[field] = Number(value);
	}
}

// 保存今日记录
async function saveTodayRecord() {
	if (!isInputValid.value) {
		return;
	}

	isSaving.value = true;
	errorMessage.value = '';

	try {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		const day = String(now.getDate()).padStart(2, '0');
		const key = `workDay_${year}${month}${day}`;

		const data = {
			work: todayRecord.value.workHours || 0,
			overtime: todayRecord.value.overtimeHours || 0,
		};

		localStorage.setItem(key, JSON.stringify(data));

		// 更新 todayRecord 数据以触发实时更新
		todayRecord.value = {
			workHours: data.work,
			overtimeHours: data.overtime,
		};

		refreshFlag.value++; // 触发重新计算

		// 显示保存成功提示
		await uni.showToast({
			title: '保存成功',
			icon: 'none',
		});
	} catch (error) {
		console.error('保存失败:', error);
		errorMessage.value = '保存失败，请重试';
	} finally {
		isSaving.value = false;
	}
}

// 编辑记录
function editRecord(day) {
	if (day.isFuture) return; // 未来日期不能编辑

	currentEditDateKey.value = day.storageKey;

	// 格式化日期显示
	currentEditDate.value = `${day.year}年${String(day.month).padStart(
		2,
		'0'
	)}月${String(day.day).padStart(2, '0')}日 ${getWeekdayName(day.date)}`;

	// 填充编辑数据
	editRecordData.value = {
		workHours: day.hasRecord ? Number(day.workHours) : 8,
		overtimeHours: day.hasRecord ? Number(day.overtimeHours) : 0,
	};

	editErrorMessage.value = '';

	// 打开弹窗
	editPopup.value.open();
}

// 获取星期名称
function getWeekdayName(date) {
	const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	return weekdays[date.getDay()];
}

// 关闭弹窗
function closePopup() {
	editPopup.value.close();
}

// 确认修改
async function confirmEdit() {
	if (!isEditInputValid.value) {
		return;
	}

	isEditing.value = true;
	editErrorMessage.value = '';

	try {
		const data = {
			work: editRecordData.value.workHours || 0,
			overtime: editRecordData.value.overtimeHours || 0,
		};

		localStorage.setItem(currentEditDateKey.value, JSON.stringify(data));
		refreshFlag.value++; // 触发重新计算

		// 关闭弹窗
		editPopup.value.close();

		// 显示修改成功提示
		await uni.showToast({
			title: '修改成功',
			icon:"none"
		});
	} catch (error) {
		console.error('修改失败:', error);
		editErrorMessage.value = '修改失败，请重试';
	} finally {
		isEditing.value = false;
	}
}

// 组件挂载时执行
onMounted(() => {
	// 检查今日是否已有记录，如果有则加载
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const key = `workDay_${year}${month}${day}`;

	const storedData = localStorage.getItem(key);
	if (storedData) {
		try {
			const data = JSON.parse(storedData);
			todayRecord.value = {
				workHours: data.work || 8,
				overtimeHours: data.overtime || 0,
			};
		} catch (e) {
			console.error('解析数据失败:', e);
		}
	}
});
</script>

<style scoped>
/* 全局样式变量 */
:root {
	--background-color: #f5f7fa;
	--text-primary: #333333;
	--text-secondary: #666666;
	--accent-color: #0083fc;
	--accent-hover: #0083fc;
	--border-color: #e0e0e0;
	--card-bg: #ffffff;
	--error-color: #00b42a;
}

/* 容器样式 */
.container {
	padding: 20rpx;
	background-color: #f5f7fa !important;
	min-height: 100vh;
}

/* 统计卡片区域 */
.stats-cards {
}

.stats-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.stat-card {
	flex: 1;
	background-color: var(--card-bg);
	text-align: center;
}

.stat-value {
	font-size: 48rpx;
	font-weight: 500;
	color: var(--text-primary);
	display: block;
	line-height: 1.2;
}

.stat-label {
	font-size: 24rpx;
	color: var(--text-secondary);
	margin-top: 8rpx;
	display: block;
}

/* 今日记录区域 */
.today-record-section {
	background-color: var(--card-bg);
	border-radius: 16rpx;
	padding: 20rpx 30rpx 30rpx 30rpx;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: 500;
	color: var(--text-primary);
	margin-bottom: 30rpx;
	display: block;
}

.record-form {
	width: 100%;
}

.form-item {
	display: flex;
	align-items: center;
}

.form-label {
	font-size: 28rpx;
	color: var(--text-primary);
	/* width: 140rpx; */
}

.form-input {
	flex: 1;
	height: 50rpx;
	width: 80rpx;
	font-size: 28rpx;
	background-color: #ffffff;
	display: flex;
	text-align: center;
	justify-content: center;
}

.form-unit {
	font-size: 28rpx;
	color: var(--text-secondary);
	width: 60rpx;
	text-align: right;
}

.save-button {
	width: 100%;
	height: 80rpx;
	background-color: var(--accent-color);
	border: none;
	border-radius: 10rpx;
	font-size: 30rpx;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 40rpx;
}

.save-button:active {
	background-color: var(--accent-hover);
	transform: scale(0.98);
}

.save-button[disabled] {
	background-color: #a0cfff;
}

.error-message {
	font-size: 24rpx;
	color: var(--error-color);
	margin-top: 10rpx;
	display: block;
}

/* 日历区域 */
.calendar-section {
	background-color: var(--card-bg);
	border-radius: 16rpx;
	padding: 30rpx;
}

.calendar-header {
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.calendar-title {
	font-size: 30rpx;
	font-weight: 500;
	color: var(--text-primary);
}

.calendar-month {
	font-size: 30rpx;
	font-weight: 500;
	color: var(--text-primary);
}

.calendar-grid {
	width: 100%;
}

.weekdays {
	display: flex;
	border-bottom: 2rpx solid var(--border-color);
	padding: 20rpx 0;
}

.weekday {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: var(--text-secondary);
}

.calendar-days {
	display: flex;
	flex-wrap: wrap;
}

.calendar-day {
	width: calc(100% / 7);
	min-height: 100rpx;
	padding: 10rpx;
	text-align: center;
	border-right: 2rpx solid #f0f0f0;
	border-bottom: 2rpx solid #f0f0f0;
	box-sizing: border-box;
	position: relative;
}

.calendar-day:nth-child(7n) {
	border-right: none;
}

/* 今天的样式 */
.calendar-day.today {
	background-color: #e3f2fd;
}

/* 其他月份的样式 */
.calendar-day.other-month {
	background-color: #fafafa;
}

.calendar-day.other-month .day-number {
	color: #cccccc;
}

/* 有记录的样式 */
.calendar-day.has-record {
	background-color: #e8f4ff;
}

.day-number {
	font-size: 28rpx;
	color: var(--text-primary);
	display: block;
}

.day-hours {
	margin-top: 10rpx;
}

.hours-text {
	font-size: 20rpx;
	color: var(--accent-color);
	font-weight: 500;
}

.no-record {
	margin-top: 10rpx;
}

.no-record-text {
	font-size: 18rpx;
	color: #cccccc;
}

/* 弹窗样式 */
.popup-container {
	background-color: #ffffff;
	border-radius: 16rpx;
	width: 500rpx;
	max-width: 500rpx;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 500;
	color: var(--text-primary);
}

.popup-close {
	font-size: 48rpx;
	color: var(--text-secondary);
	line-height: 1;
}

.popup-body {
	padding: 30rpx;
}

.popup-date {
	font-size: 28rpx;
	color: var(--text-secondary);
	margin-bottom: 20rpx;
	display: block;
}

.popup-footer {
	display: flex;
	border-top: 2rpx solid #f0f0f0;
}

.cancel-button {
	flex: 1;
	height: 80rpx;
	background-color: #f5f5f5;
	color: var(--text-primary);
	border: none;
	border-radius: 0;
	font-size: 28rpx;
}

.confirm-button {
	flex: 1;
	height: 80rpx;
	background-color: var(--accent-color);
	border: none;
	border-radius: 0;
	font-size: 28rpx;
}

.confirm-button[disabled] {
	background-color: #a0cfff;
}

hr {
	border: none;
	height: 2rpx;
	background-color: #e9ecef;
	margin: 20rpx 0;
}
</style>
